package com.ajun.service;

import com.ajun.common.entity.R;
import com.ajun.entity.Order;
import com.ajun.entity.OrderMessage;
import com.ajun.mapper.OrderMapper;
import com.ajun.mapper.OrderMessageMapper;
import com.ajun.producer.OrderProducer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 基于 MQ 的业务处理
 *
 * @author LiJun
 * @date 2021-07-15
 */
@Slf4j
@Service
public class OrderService {

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private OrderMessageMapper orderMessageMapper;

    @Resource
    private OrderProducer orderProducer;

    @Transactional(rollbackFor = Exception.class)
    public R<Boolean> createOrder(Order order) {
        // 保存订单信息
        int count = orderMapper.insert(order);

        // 保存消息冗余表
        OrderMessage orderMessage = new OrderMessage();
        orderMessage.setOrderId(order.getOrderId());
        orderMessage.setOrderContent(order.getOrderContent());
        orderMessage.setStatus((byte) 0);
        orderMessage.setUniqueId(1);
        orderMessageMapper.insert(orderMessage);

        // 发送消息给运单系统
        orderProducer.sendOrderMsg(order);
        return R.ok(count == 1);
    }
}
